<template>
  <van-collapse-item
    :title="`讲课费（小计：￥${totalPrice}）`"
    name="speakerPrice"
  >
    <div class="card-container">
      <div>
        <van-empty v-if="!speakerList.length" description="暂未设置讲者" />
        <div class="speaker_list" v-else>
          <div class="speaker_item title">
            <div></div>
            <div>税前</div>
            <div>税后</div>
            <div></div>
          </div>
          <div
            class="speaker_item"
            v-for="item in speakerList"
            :key="item.speakerId"
          >
            <div>{{ item.speakerName  }}</div>
            <div>
              <span v-if="item.speakerAppearanceFeePretax">￥{{ getPrice(item.speakerAppearanceFeePretax) }}</span>
              <span v-else>--</span>
            </div>
            <div @click="clickModifyFee(item)">
              <span :class="isAllowModifyFee(item) ? 'text-primary' : ''">
                <span v-if="item.speakerAppearanceFeeAftertax">￥{{ getPrice(item.speakerAppearanceFeeAftertax) }}</span>
                <span v-else-if="detail && detail.state == 2">--</span>
                <span v-else>请选择</span>
              </span>
            </div>
            <div v-if="isShowQrCode(item)">
              <div v-if="(item.laowuUrl || []).length" class="text-success">已签署</div>
              <div v-else-if="item.speakerStatus == 4">讲者信息待完善</div>
              <div v-else-if="item.speakerStatus == 1">讲者信息待审核</div>
              <div v-else class="text-primary" @click="clickShowQrcode(item)">协议二维码</div>
            </div>
            <div v-else-if="detail && detail.state ==2 && !item.speakerAppearanceFeePretax"></div>
            <div v-else>{{ getMapLabel('speakerType', item.speakerRole) }}</div>
          </div>
        </div>
      </div>
    </div>
  </van-collapse-item>

  <van-dialog
		confirm-button-text="关闭"
		@confirm="qr.visible = false"
		style="text-align: center"
		v-model:show="qr.visible"
	>
    <div v-if="qr.imgUrl" class="agree_preview_img">
      <img class="agree_preview_img__inner" :src="qr.imgUrl" alt="">
    </div>
    <div v-else id="agree_preview_box" class="agree_preview_box">
      <h2 class="agree_title">{{qr.userName }}教授劳务协议二维码</h2>
      <p class="meeting_date">会议时间：{{ detail.startTime }}</p>
		  <vue-qr :text="qr.content" :size="260"></vue-qr>
    </div>
    <p class="agree_preview_desc">长按二维码进行保存</p>
	</van-dialog>

  <van-action-sheet
    v-model:show="modifyFee.visible"
    :actions="modifyFee.list"
    cancel-text="取消"
    close-on-click-action
    @select="clickSelectModifyFee"
  />
</template>

<script setup>
  import { toRefs, computed, reactive, onMounted } from 'vue'
  import useConstant from '@/hooks/useConstant';
  import useUtils from '@/hooks/useUtils'
  import { useRoute } from 'vue-router'
  import { useStore } from 'vuex'
  import html2canvas from 'html2canvas'

  const store = useStore();
  const route = useRoute();
  const props = defineProps({
    speakerList: {
      type: Array,
      default: () => ([])
    },
    detail: {
      type: Object,
      default: () => {}
    }
  })

  const qr = reactive({
    visible: false,
    content: '',
    userName: '',
    imgUrl: ``
  })
  const { getPrice } = useUtils();
  const { getMapLabel } = useConstant();

  const priceConfig = computed(() => {
    return store.state.tenant.config.speakerFeeConfig ? JSON.parse(store.state.tenant.config.speakerFeeConfig) : {}
  })

  const clickShowQrcode = (item) => {
    if ((item.laowuUrl || []).length) return
    const { detail } = toRefs(props);
    const tenanId = store.state.tenant.config.tenantId
    qr.imgUrl = '';
    qr.userName = item.speakerName;
    qr.content = `http://rongchang-wx-front.skyfar.net/#/agreement/${detail.value.id}/${item.speakerId}`
    qr.visible = true

    setTimeout(() => {
      saveImage()
    }, 200)
  }

  const totalPrice = computed(() => {
    const { speakerList } = toRefs(props);
    const price = speakerList.value.reduce((val, item) => val + item.speakerAppearanceFeePretax, 0)
   
    return getPrice(price);
  })

  const modifyFee = reactive({
    visible: false,
    list: [],
    currentSpeaker: null,
  })
  //是否显示协议二维码字样
  function isShowQrCode (item) {
    const { detail } = toRefs(props)
    if (detail.value?.state == 2) {
      if (item.speakerAppearanceFeePretax) {
        return true
      }
    }
    return false
  }
  function isAllowModifyFee (val) {
    if (!route.query.handleType || route.query.handleType === 'update') {
      // if (val.speakerRole != 3) return true
      return true
    }
    return false
  }

  function getRolePricePriceOptions (role) {
    return priceConfig.value.find(item => item.role == role)
  }
  function clickModifyFee (item) {
    if (!isAllowModifyFee(item)) return
    
    modifyFee.list = (getRolePricePriceOptions(item.speakerRole)?.fee || []).map(item => ({
      ...item,
      name: '￥' + getPrice(item.aftertax),
      value: item.aftertax
    }))
    // if (item.speakerRole == 1) {
    //   modifyFee.list = [
    //     { name: '￥3000.00', value: 3000 },
    //     { name: '￥2000.00', value: 2000 },
    //     { name: '￥1000.00', value: 1000 }
    //   ]
    // }
    // if (item.speakerRole == 2) {
    //   modifyFee.list = [
    //     { name: '￥2000.00', value: 2000 },
    //     { name: '￥1000.00', value: 1000 }
    //   ]
    // }
    
    modifyFee.currentSpeaker = item
    modifyFee.visible = true
  }

  function clickSelectModifyFee (val) {
    modifyFee.currentSpeaker.speakerAppearanceFeeAftertax = val.aftertax
    modifyFee.currentSpeaker.speakerAppearanceFeePretax = val.pretax
    // modifyFee.currentSpeaker.speakerAppearanceFeePretax = getMapLabel('priceBefore', val.value)
  }

  // 长按保存图片
  const saveImage = () => {
    const targetDom = document.getElementById('agree_preview_box')
    const copyDom = targetDom.cloneNode(true)
    copyDom.className = 'agree_preview_box'
    copyDom.style.width = targetDom.scrollWidth + 'px'
    copyDom.style.height = targetDom.scrollHeight + 'px'
    document.body.appendChild(copyDom)

    html2canvas(copyDom,{
        allowTaint: false,
        useCORS: true,
        backgroundColor: 'transparent',
        width: targetDom.clientWidth,
        height: targetDom.clientHeight,
    }).then(canvas => {
        // showDom.value = false
        document.body.removeChild(copyDom)
        qr.imgUrl = canvas.toDataURL('image/png');
        console.log(qr.imgUrl)
    })
  }

</script>

<style lang="less" scoped>
  .speaker_list{
    padding: 10px;
    .speaker_item {
      display: flex;
      padding: 10px 0;
      font-size: 12px;
      text-align: center;
      >div {
        &:nth-child(1) {
          flex: 0 0 50px;
        }
        &:nth-child(2) {
          flex: 0 0 90px;
          color: #000;
        }
        &:nth-child(3) {
          flex: 0 0 90px;
          color: #000;
        }
        &:nth-child(4) {
          flex: auto;
        }
      }
      &.title {
        color: #000;
      }
    }
  }

  .agree_preview_box{
    padding-top:6px;
    width: 260px;
    margin: 0 auto;
    background-color: #fff;
    text-align: center;
  }
  .agree_title {
    font-size: 18px;
    padding-top: 10px;
  }
  .meeting_date {
    font-size: 14px;
    color: #555;
  }
  .agree_preview_img {
    text-align: center;
    &__inner {
      width: 260px;
    }
  }
  .agree_preview_desc {
    margin: 0;
    font-size: 14px;
    padding-bottom: 20px;
    color: rgb(121, 0, 0);
    font-weight: bold;
  }
</style>